import dayjs from 'dayjs'

import { createSlice } from '@reduxjs/toolkit'


const ticketSlice = createSlice({
  name: 'ticket',
  initialState: {
    start: '北京',
    end: '上海',
    onlyCRH: false,
    date: dayjs().format('YYYY-MM-DD'),
    searchHistory:[]
  },
 
  reducers: {
    updateFromAndTo(state) {
      
      const temp = state.start
      state.start = state.end
      state.end = temp
    },
  

    updateOnlyCRH(state, action) {
      console.log(action)
      state.onlyCRH = action.payload
    },
    // 更新出发的日期
    updateDate(state, action) {
      console.log(action.payload);
      state.date= dayjs(action.payload).format('YYYY-MM-DD')
    },
   
    updateCity(state, action) {
      if (action.payload.type === 'end') {
        state.end = action.payload.city
      } else {
        state.start = action.payload.city
      }
    },
    
    searchHistory(state, action){
      state.searchHistory.unshift(action.payload)
      const set=new Set(state.searchHistory)
      state.searchHistory=Array.from(set)
    }
  }
})

// 向外导出当前切片的 reducer
export default ticketSlice.reducer

// 向外导出更新数据的函数
export const { updateFromAndTo, updateOnlyCRH, updateDate, updateCity,searchHistory } =
  ticketSlice.actions
